package projectVersion;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

import projectVersion.ResLoader.State;

public abstract class Handler {
	
	protected String filePath;
	
	public Handler(String path) {
		this.filePath = path;
	}

	public void handle() throws FileNotFoundException {
		File f = new File(this.filePath);
		if (!f.exists()) {
			System.out.println("文件不存在！");
			return ;
		}
		final StringBuilder sb = new StringBuilder();
		FileInputStream fis = new FileInputStream(f);
		new ResLoader(fis) {
			
			@Override
			void onReadLine(String lineStr, State state) {
				boolean isHandle = custHandleLine(lineStr, state, sb);
				if (isHandle) {
					sb.append("\n");
				} else {
					sb.append(lineStr).append("\n");
				}
			}
		};
		
		// 重新写入文件
		BufferedWriter writer = null;
		String content = sb.toString();
		try {
			writer = new BufferedWriter(new FileWriter(this.filePath));
			writer.write(content);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (Exception e2) {
					writer = null;
				}
			}
		}
		
	}
	
	abstract boolean custHandleLine(String lineStr, State state, StringBuilder sb);
}
